package cn.pconline.autoclub.service.bbssync;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.gelivable.dao.GeliUtils;
import org.springframework.beans.factory.annotation.Autowired;

import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.ClubIntegral;
import cn.pconline.autoclub.entity.ClubMember;
import cn.pconline.autoclub.entity.DynaImage;
import cn.pconline.autoclub.entity.DynaInfo;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.service.DynaService;
import cn.pconline.autoclub.service.PetrolService;
import cn.pconline.autoclub.util.dyna.TopicDyna;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * @author zhouruxuan
 * @date 2014年12月4日 上午11:45:19
 */
public class SyncSetRecommendService extends BbsSyncPetrolService {
	@Autowired
	private DynaService dynaService;
	@Autowired
	private PetrolService petrolService;
	@Autowired
	private SyncCreateTopicService syncCreateTopicService;
	
	//private TopicDyna topicDyna;
	
	//private ClubIntegral clubIntegral;
	
	//private long clubId;
	
	@Override
    protected int addPetroltoMember(ClubMember clubMember, JSONObject msg) {
	    ClubIntegral clubIntegral = petrolService.getById(PetrolService.ADD_PERSONAL_PETROL_ITEM_RECOMMEND);
	    String reason = clubIntegral.getName() + "(topic-" + getTopicId(msg) + ")";
        petrolService.addOnlyPersonWithinLimit(clubMember, (int)clubIntegral.getIntegralId(), clubIntegral.getPetrol(), reason, false);
        return clubIntegral.getPetrol();
    }

    @Override
    protected int addPetroltoClub(Club club, JSONObject msg) {
        ClubIntegral clubIntegral = petrolService.getById(PetrolService.ADD_PERSONAL_PETROL_ITEM_RECOMMEND);
        String reason = clubIntegral.getName() + "(topic-" + getTopicId(msg) + ")";
        petrolService.addToClubWithinLimit(club.getClubId(),(int) clubIntegral.getIntegralId(), clubIntegral.getPetrol(), reason, false);
        return clubIntegral.getPetrol();
    }
    
    @Override
    protected long getUserId(JSONObject msg) {
        return msg.getLongValue("topicAuthorId");
    }
	
	@Override
	public void process(JSONObject msg, ClubMember clubMember) {
	    
		//验证用户
	    long userId = getUserId(msg);
		if (userId <= 0L) {
            log.info("not userId-{}", userId);
            return;
        }

        //判断用户是否登录
        User user = userService.authUser(userId);
        if (user == null || user.getUid() == 0L) {
            log.info("not found user-{}", userId);
            return;
        }
        long clubId = 0;
        if(clubMember != null) {
            clubId = clubMember.getClubId();
        }
        TopicDyna topicDyna = parseActionLog2DynaInfo(msg, clubId);
        //设置帖子对象
        DynaInfo isExistInfo = dynaService.findDynaInfoByTopicId(topicDyna.getTopicId(), topicDyna.getCreateDate());
        //如果帖子存在，就以原来的油值为准
        if (isExistInfo != null) {
            TopicDyna topicDyna_exist = parseActionLog2DynaInfo(msg, clubId);
            topicDyna_exist.setPetrol(isExistInfo.getPetrol());
            log.info("topicDyna_exist: {}", GeliUtils.getDao().object2String(topicDyna_exist));
            List<DynaImage> dynaImages = parseActionLog2DynaImages(msg, userId);
            dynaService.createTopicDyna(topicDyna_exist, dynaImages);
        } else {//如果帖子不存在就走正常的流程
        	//设置topic对象 
            TopicDyna topicDyna_new = this.parseActionLog2DynaInfo(msg, clubId);
            if(clubMember != null) {
                Club club = clubService.getClub(clubMember.getClubId());
                if(club != null && club.getStatus() == Club.STATUS_PASS) {
                    // 创建帖子油值
                    int petrol = petrolService.getById(PetrolService.ADD_PERSONAL_PETROL_ITEM_TOPIC).getPetrol(); // 油值表
                    // 创建帖子
                    topicDyna_new.setPetrol(petrol);
                }
            }
            log.info("topicDyna_new: {}", GeliUtils.getDao().object2String(topicDyna_new));
            List<DynaImage> dynaImages = this.parseActionLog2DynaImages(msg, userId);
            dynaService.createTopicDyna(topicDyna_new, dynaImages);
        }
        
        long topicId = topicDyna.getTopicId();
        Date createAt = topicDyna.getCreateDate();
        
        int petrol = this.calculateDynaPetrol(topicDyna);
        log.info("set recommend add petrol: {}", petrol);
        dynaService.setRecommend(topicId, createAt, petrol);
        
	}
	
	/**
	 * @param json转topic
	 * @param clubId
	 * @return
	 */
    private TopicDyna parseActionLog2DynaInfo(JSONObject msg, long clubId) {
        TopicDyna topicDyna = new TopicDyna();
        topicDyna.setTopicId(msg.getLongValue("topicId"));
        topicDyna.setClubId(clubId);
        topicDyna.setForumId(msg.getLongValue("forumId"));
        topicDyna.setUserId(msg.getLongValue("topicAuthorId"));
        topicDyna.setForumName(StringUtils.defaultString(msg.getString("forumName")));
        topicDyna.setLastPostAt(new Date(msg.getLongValue("lastPostAt")));
        topicDyna.setCreateDate(new Date(msg.getLongValue("topicCreateAt")));
        topicDyna.setLastPostBy(msg.getLongValue("topicAuthorId"));
        topicDyna.setLastPostName(msg.getString("topicAuthorName"));
        topicDyna.setMessage(StringUtils.defaultString(msg.getString("postMessage")));
        topicDyna.setTopicTitle(StringUtils.defaultString(msg.getString("title")));
        topicDyna.setPick(msg.getIntValue("pick") != DynaInfo.PICK_NO ? DynaInfo.PICK_YES : DynaInfo.PICK_NO);
        //topicDyna.setRecommend(msg.getIntValue("recommend") != DynaInfo.TYPE_UNRECOMMEND ? DynaInfo.TYPE_RECOMMEND: DynaInfo.TYPE_UNRECOMMEND);
        topicDyna.setPostCount(msg.getIntValue("topicReplyCount"));
        topicDyna.setCreateName(msg.getString("topicAuthorName"));//论坛传的是nickname
        topicDyna.setType(msg.getString("type"));//帖子类型，question为提问帖标记
        return topicDyna;
    }
    
    /**
     * 计算设置精华油值
     * @param topicDyna
     * @param typeId
     * @return
     */
    private int calculateDynaPetrol(TopicDyna topicDyna) {
    	ClubIntegral clubIntegral = petrolService.getById(PetrolService.ADD_PERSONAL_PETROL_ITEM_RECOMMEND);
        int dynaPetrol = clubIntegral.getPetrol();
        return dynaPetrol;
    }
    
    /**
     * 帖子图片列表
     * @param msg
     * @param userId
     * @return
     */
    private List<DynaImage> parseActionLog2DynaImages(JSONObject msg, long userId) {
    	String imageString = msg.getString("images");
        if (imageString == null) {
            return null;
        } else {
            JSONArray jsonArray = JSONArray.parseArray(imageString);
            List<DynaImage> list = new ArrayList<DynaImage>();
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject json = JSONObject.parseObject(jsonArray.getString(i));
                DynaImage dynaImage = new DynaImage();
                dynaImage.setSeq(json.getIntValue("seq"));
                dynaImage.setUrl(json.getString("url"));
                dynaImage.setWidth(json.getIntValue("width"));
                dynaImage.setHeight(json.getIntValue("height"));
                if (StringUtils.isBlank(dynaImage.getUrl())) {
                    continue;
                }
                list.add(dynaImage);
            }
            return list;
        }
    }
    
    private long getTopicId(JSONObject msg) {
        return msg.getLongValue("topicId");
    }
}
